#include "videosender.h"
#include <QDebug>
#include <QBuffer>
#include <QString>

VideoSender::VideoSender(QString ip, quint16 port, QObject *parent) : QObject(parent), ip(ip), port(port)
{
    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::AnyIPv4, port, QAbstractSocket::ReuseAddressHint);
    socket->setSocketOption(QAbstractSocket::SendBufferSizeSocketOption, 300*2048);
    socket->joinMulticastGroup(QHostAddress(ip));
}

void VideoSender::sendVideo(QByteArray byte)
{
    int unitBytes = 1024;
    int byteCount = byte.length(); // 图片大小
    int writeBytes = 0; // 以写入大小

    int currentBytes = byteCount - writeBytes; // 本次写入的大小
    int i = 0;
    while (writeBytes < byteCount)
    {
        ImagePackage pack;
        memset(&pack, 0, sizeof(ImagePackage));
        pack.packNum = i++;
        currentBytes = (unitBytes < (byteCount - writeBytes) ? unitBytes : (byteCount - writeBytes));
        memcpy(pack.data, byte.data() + writeBytes, currentBytes);
        writeBytes += unitBytes;
        pack.packTaken = currentBytes; // 设置当前包中数据的大小
        socket->writeDatagram((char *)&pack, sizeof(ImagePackage), QHostAddress(ip), port);
    }
}

void VideoSender::closeCamera()
{
    ImagePackage pack;
    memset(&pack, 0, sizeof(ImagePackage));
    pack.packNum = -1;
    socket->writeDatagram((char *)&pack, sizeof(ImagePackage), QHostAddress(ip), port);
}
